package com.naire.modul.project.dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.common.dao.GeneralDaoImpl;
import net.common.service.PageBean;
import net.common.util.BeanUtils;
import net.common.util.DateUtils;

import com.naire.modul.projecperiods.pojo.Projecperiods;
import com.naire.modul.projecperiods.vo.ProjecperiodsVo;
import com.naire.modul.project.dao.ProjectDao;
import com.naire.modul.project.pojo.Project;
import com.naire.modul.project.vo.ProjectVo;

public class ProjectDaoImpl extends GeneralDaoImpl implements ProjectDao {

	@SuppressWarnings("unchecked")
	public List<ProjectVo> searchProjectAndPeriods() throws Exception {
		List<ProjectVo> list = new ArrayList<ProjectVo>();
		StringBuilder hql = new StringBuilder("from Project where flag=0");
		List<Project> l = hibernateHandler.query(hql);
		for(Project p : l) {
			ProjectVo pv = new ProjectVo();
			BeanUtils.copyProperties(p, pv);
			Iterator<Projecperiods> it = p.getPeriods().iterator();
			while(it.hasNext()) {
				ProjecperiodsVo v = new ProjecperiodsVo();
				BeanUtils.copyProperties(it.next(), v);
				v.setName(v.getPeriods_name() + "(" + DateUtils.dateToString(v.getStart_date()) + "~" + DateUtils.dateToString(v.getEnd_date()) + ")");
				pv.getData().add(v);
			}
			list.add(pv);
		}
		return list;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<ProjectVo> search(PageBean pageBean) throws Exception {
		StringBuilder hql = new StringBuilder("from Project where flag=0");
		List<ProjectVo> d = new ArrayList<ProjectVo>();
		List<Project> l = hibernateHandler.query(hql, pageBean);
		for(Project bean : l) {
			ProjectVo dv = new ProjectVo();
			BeanUtils.copyProperties(bean, dv);
			d.add(dv);
		}
		return d;
	}

	@Override
	public Integer insert(ProjectVo bean) throws Exception {
		Project pojo = new Project();
		BeanUtils.copyProperties(bean, pojo);
		hibernateHandler.insert(pojo);
		return pojo.getProject_id();
	}

	@Override
	public void update(ProjectVo bean) throws Exception {
		Project pojo = (Project)hibernateHandler.find(Project.class, bean.getProject_id());
		BeanUtils.copyProperties(bean, pojo);
		hibernateHandler.update(pojo);
	}

	@Override
	public void updateFlag(ProjectVo bean) throws Exception {
		update(bean);
	}

	@Override
	public ProjectVo find(Integer id) throws Exception {
		Project pojo = (Project)hibernateHandler.find(Project.class, id);
		ProjectVo bean = new ProjectVo();
		BeanUtils.copyProperties(pojo, bean);
		return bean;
	}
}
